package com.boho.ecp.member.action;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import cn.boho.framework.actions.ActionImp;
import cn.boho.framework.context.ActionContext;
import cn.boho.framework.service.MessageService;

import com.boho.ecp.base.model.Product;
import com.boho.ecp.base.model.UserCookie;
import com.boho.ecp.base.service.CookieService;
import com.boho.ecp.constant.Member;
import com.boho.ecp.util.JsonUtils;

public class MemberCookieAction extends ActionImp {

	private final static String PARAM_COOKIE = "PARAM_COOKIE";
	
	@Override
	protected void doException(ActionContext atx, Exception ex) {
		atx.setErrorContext("MEMBER_COOKIE_ERROR", MessageService.getMessage("MEMBER_COOKIE_ERROR"), ex);
	}

	@Override
	protected int performExecute(ActionContext atx) throws Exception {
		Integer memberId = (Integer)atx.getSessionValue(Member.MEMBER_ID_SESSION);
		String cookie = CookieService.getValue(atx, PARAM_COOKIE);
		if(StringUtils.isEmpty(cookie)){
			cookie = "{uid:0,product:[],items:0}";
		}
		
		UserCookie userCookie = null;
		try {
			userCookie = JsonUtils.fromJson(cookie, UserCookie.class);
		} catch (Exception e) {
			return 0;
		}
		
		List<Product> product = userCookie.getProduct();
		boolean loginStatus = true;
		if(memberId == null){
			memberId = userCookie.getUid();
			loginStatus = false;
		}
		
		atx.setValue("STATUS", loginStatus);
		atx.setValue("MEMBER_ID", memberId);
		atx.setValue("COOKIE_PRODUCT", product);
		
		return 1;
	}

	@Override
	protected int verifyParameters(ActionContext atx) throws Exception {
		return 1;
	}
}
